<?php

namespace App\Utility;


use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;



class ImageUtility
{

    private static array $allow_ext = ['png','jpg','gif','jpeg'];


    public static function save(UploadedFile $file,$folder,$model_id,$max_width=false)
    {

        //获取文件后缀
        $extension = strtolower($file->extension()) ?: 'png';

        if (!in_array($extension,self::$allow_ext)) return false;

        $folder_name = "upload/images/{$folder}/".date('Ym/d',time());
        $absFolder = public_path().'/'.$folder_name;
        $file_name = md5($model_id.time()).'.'.$extension;

        $file->move($absFolder, $file_name);


        if ($max_width && $extension != 'gif') {
            self::reduceSize($absFolder.'/'.$file_name,$max_width);
        }

        self::delete($folder,$model_id);

        return config('app.url')."/$folder_name/$file_name";
    }


    public static function delete($folder,$model_id)
    {

        $abs_file_path = null;
        if ($folder == 'avatar') {
            $user = DB::table('users')->find($model_id);
            $avatar = $user->avatar;
            $abs_file_path = public_path().Str::after($avatar, config('app.url'));
        }

        if (File::exists($abs_file_path)) {
            File::delete($abs_file_path);
        }

    }


    public static function reduceSize($file_path,$max_width)
    {
        $manager = new ImageManager(Driver::class);

        $image = $manager->read($file_path);

        if ($image->width() > $max_width) {
            $ratio = $max_width / $image->width();
            $image->resize($max_width,$ratio * $image->height());
            $image->save();
        }
    }
}
